package ReadCount;
use lib "$ENV{MYSQL_DRAW}/lib";
use MyTools;
use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
 
@ISA = qw(Exporter AutoLoader);

@EXPORT = qw( readReadCount );

use Data::Dumper;

sub readReadCount {
	my ($dbh, $prefix, $modifier, $field_list) = @_;
	open(FIN, "tail $prefix.readct |") || die "cannot open $prefix.readct\n";
	my %hash;
# INFO  16:06:43,593 TraversalEngine - 1059978 reads were filtered out during traversal out of 8200692 total (12.93%) 
# INFO  16:06:43,594 TraversalEngine -   -> 883762 reads (10.78% of total) failing DuplicateReadFilter 
# INFO  16:06:43,594 TraversalEngine -   -> 145433 reads (1.77% of total) failing MappingQualityZeroFilter 
# INFO  16:06:43,595 TraversalEngine -   -> 30783 reads (0.38% of total) failing UnmappedReadFilter 
	while (<FIN>) {
		if (/traversal out of /) {
			#special read-only variables $` and $& and $' to find what was matched before, during and after the seach
			my ($num, $field) = split(/ /, $');
			$hash{$field} = $num
		}
		else {
			/\((\d+\.\d+)% of total\) failing (\w+Filter)/;
			next unless defined($1) && defined($2);
			$hash{$2} = $1;
		}
	}
	close FIN;
	my $RV;
	foreach my $fd (@{$field_list}) {
		my $metric_id = MyTools::fetchrow1col1_arrayref($dbh, "select MIID from MetricInfo where ", {'FieldName' => $fd, 'Modifier' => $modifier, 'ReportName' => 'readct'}) or die "readct Field $fd $modifier not found\n";
#		printf STDERR "$fd\t$metric_id\n";
		my $fd_val = "NA";
		foreach my $line (keys %hash) {
			if ($line =~ /$fd/) {
				$fd_val = $hash{$line};
				last;
			}
		}
		$RV->{$metric_id}->{'value'} = $fd_val;
		$RV->{$metric_id}->{'field_name'} = $fd;
	}
	return $RV;
}
1;

